//
//  HSImageUploader.m
//  AFNetworking
//
//  Created by huang on 2018/8/16.
//

#import "HSImageUploader.h"
#import "AFNetworking.h"

@implementation HSImageUploader

//防止内存泄露
+ (AFHTTPSessionManager *)sharedHttpSession
{
    static AFHTTPSessionManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 10;
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript",@"text/plain", nil];
    });
    return manager;
}

#pragma mark 取消所有请求
+ (void)cancelAllRequest
{
    AFHTTPSessionManager *manager = [HSImageUploader sharedHttpSession];
    [manager.operationQueue cancelAllOperations];
}

+ (instancetype)shareManager
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        //1.初始化数据
        self.compressionQuality = 0.28;
        self.tagName = @"file";
        self.mineType = @"image/png";
    }
    return self;
}

#pragma mark 上传单张图片
- (void)imageUploader:(UIImage *)image success:(ImageUploaderSuccessBlock)success failure:(ImageUploaderFailureBlock)failure
{
    [self imageUploader:image progress:nil success:success failure:failure];
}

- (void)imageUploader:(UIImage *)image progress:(ImageUploaderProgressBlock)progress success:(ImageUploaderSuccessBlock)success failure:(ImageUploaderFailureBlock)failure
{
    [self imageUploaderWithImages:@[image] progress:progress success:success failure:failure];
}

#pragma mark 多张图片
- (void)imageUploaderWithImages:(NSArray *)images success:(ImageUploaderSuccessBlock)success failure:(ImageUploaderFailureBlock)failure
{
    [self imageUploaderWithImages:images progress:nil success:success failure:failure];
}

- (void)imageUploaderWithImages:(NSArray *)images progress:(ImageUploaderProgressBlock)progress success:(ImageUploaderSuccessBlock)success failure:(ImageUploaderFailureBlock)failure
{
    if (self.uploaderPath.length == 0) {
        return;
    }
    
    AFHTTPSessionManager *manager = [HSImageUploader sharedHttpSession];
    manager.operationQueue.maxConcurrentOperationCount = 4;
    [manager POST:self.uploaderPath parameters:self.params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < images.count; i ++) {
            
            //1.文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
            
            //2.转为 NSData
            NSData *imageData = [self compressionImage:images[i]];
            
            NSString *nameStr = self.tagName;
            if (i > 0) {
                nameStr = [NSString stringWithFormat:@"%@%d",self.tagName,i + 1];
            }
            
            //3.拼接数据
            [formData appendPartWithFileData:imageData name:nameStr fileName:fileName mimeType:self.mineType];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (NSData *)compressionImage:(UIImage *)image
{
    return UIImageJPEGRepresentation(image, self.compressionQuality);
}

@end
